/*
  *   @Author: 1296
  *   @Date: 2025-03-20
  *   @Description: 全局路由守卫
*/
import i18n from "@/i18n";
import { createRouter, createWebHistory } from 'vue-router'
import HomePage from '@/pages/HomePage.vue'
import PersonalPage from  '@/pages/PersonalPage.vue'
import AboutProject from '@/pages/AboutProject.vue'
import AboutUs from '@/pages/AboutUs.vue'
import LoginAndRegister from "@/pages/LoginAndRegister.vue";
import NotFound from '@/pages/error/NotFound.vue';
import SystemDesign from "@/pages/SystemDesign.vue";
import DemandAnalysis from "@/pages/DemandAnalysis.vue";
import InterfaceDoc from "@/pages/InterfaceDoc.vue";
import MyProfile from '@/pages/MyProfile.vue'
import Setting from '@/pages/SystemSetting.vue'
import UnAuthorized from "@/pages/error/UnAuthorized.vue";
import TestPage from "@/pages/test/TestPage.vue";
import LanguageSettings from "@/components/settings/LanguageSettings.vue";
import forgotPassword from "@/pages/forgotPassword.vue"
import CourseDetailPage from "@/components/teacher/CourseDetailPage.vue";
import NormalSign from "@/components/student/signs/NormalSign.vue";
import DraftSign from "@/components/student/signs/DraftSign.vue";
import PositionSign from "@/components/student/signs/PositionSign.vue";
import QRCodeSign from "@/components/student/signs/QRCodeSign.vue";
import PINSign from "@/components/student/signs/PINSign.vue";
import Dashboard from "@/pages/Dashboard.vue";
import VerificationComponent from "@/components/verification/VerificationComponent.vue";
import recordDetail from "@/components/teacher/recordDetail.vue";
import Instruction from "@/pages/Instruction.vue";

const routes = [
    {
        path: '/homePage',
        component: HomePage,
        meta: { title: 'HomePage', layout: 'DefaultLayout', requiresAuth: false }
    },
    {
        path: '/personalPage',
        component: PersonalPage,
        meta: { title: 'PersonalPage', layout: 'DefaultLayout', requiresAuth: false }
    },
    {
        path: '/aboutProject',
        component: AboutProject,
        meta: { title: 'AboutProject', layout: 'DefaultLayout', requiresAuth: false }
    },
    {
        path: '/aboutUs',
        component: AboutUs,
        meta: { title: 'AboutUs', layout: 'DefaultLayout', requiresAuth: false }
    },
    {
      path: '/languageSettings',
      component: LanguageSettings,
      meta: { title: 'floatingButtons.languageSettings', layout: 'LoginRegisterLayout', requiresAuth: false }
    },
    {
        path: '/loginAndRegister',
        component: LoginAndRegister,
        meta: { title: 'LoginAndRegister', layout: 'LoginRegisterLayout', requiresAuth: false }
    },
    {
        path: '/forgotPassword',
        component: forgotPassword,
        meta: { title: 'login.forgotPassword', layout: 'LoginRegisterLayout', requiresAuth: false }
    },
    // 权限控制
    {
        path: '/systemDesign',
        component: SystemDesign,
        meta: {title: 'systemDesign', layout: 'EmptyLayout'}
    },
    {
        path: '/demandAnalysis',
        component: DemandAnalysis,
        meta: {title: 'demandAnalysis', layout: 'EmptyLayout'}
    },
    {
        path: '/interfaceDoc',
        component: InterfaceDoc,
        meta: {title: 'interfaceDoc', layout: 'EmptyLayout'}
    },
    {
        path: '/instruction',
        component: Instruction,
        meta: { title: 'instruction', layout: 'EmptyLayout' }
    },
    {
        path: '/:jobCode',
        // component: PersonalPage,
        meta: { requiresAuth: true , layout: 'AfterLoginLayout'},
        children: [
            {
              path: 'dashboard',
              name: 'Dashboard',
              component: Dashboard,
              meta: { title: 'dashboard', validateUser: true }
            },
            {
                path: 'setting',
                name: 'UserSettings',
                component: Setting,
                meta: { title: 'systemSettings', validateUser: true }
            },
            {
                path: 'myProfile',
                name: 'UserProfile',
                component: MyProfile,
                meta: { title: 'MyProfile', validateUser: true }
            },
            {
                path: 'personalPage',
                component: PersonalPage,
                meta: { title: 'PersonalPage' }
            },
            {
                path: 'course/:id',
                name: 'CourseDetail',
                component: CourseDetailPage,
                meta: { title: 'CourseDetail', layout: 'LoginRegisterLayout' ,validateUser: true, requiresRole: '1' }
            },
            {
                path: 'recordDetail',
                name: 'recordDetail',
                component: recordDetail,
                meta: { title: 'recordDetail', layout: 'LoginRegisterLayout', validateUser: true, requiresRole: '1' }
            },
            {
                path: 'commonCheckIn/:id',
                name: 'NormalSign',
                component: NormalSign,
                meta: { title: 'normalSign', layout: 'EmptyLayout', validateUser: true, requiresRole: '0' }
            },
            {
                path: 'gestureCheckIn/:id',
                name: 'DraftSign',
                component: DraftSign,
                meta: { title: 'draftSign', layout: 'EmptyLayout', validateUser: true, requiresRole: '0' }
            },
            {
                path: 'locationCheckIn/:id',
                name: 'PositionSign',
                component: PositionSign,
                meta: { title: 'positionSign', layout: 'EmptyLayout', validateUser: true, requiresRole: '0' }
            },
            {
                path: 'codeCheckIn/:id',
                name: 'PINSign',
                component: PINSign,
                meta: { title: 'PINSign', layout: 'EmptyLayout', validateUser: true, requiresRole: '0' }
            },
            {
                path: 'qrcodeCheckIn/:id',
                name: 'QRCodeSign',
                component: QRCodeSign,
                meta: { title: 'QRCodeSign', layout: 'EmptyLayout', validateUser: true, requiresRole: '0' }
            }
        ]
    },
    {
        path: '/verification/:requiresVerify',
        name: 'Verification',
        component: VerificationComponent,
        meta: { title: 'Verification', layout: 'EmptyLayout', requiresAuth: true }
    },
    {
        path: '/setting',
        redirect: () => {
            const jobCode = sessionStorage.getItem('jobCode')
            return jobCode ? `/${jobCode}/setting` : '/loginAndRegister'
        }
    },
    {
        path: '/myProfile',
        redirect: () => {
            const jobCode = sessionStorage.getItem('jobCode')
            return jobCode ? `/${jobCode}/myProfile` : '/loginAndRegister'
        }
    },
    /*
    * 代码请在此处上方设计。
    * */
    {
        path: '/unAuthorized',
        name: 'UnAuthorized',
        component: UnAuthorized,
        meta: { title: 'unAuthorized', layout: "EmptyLayout" }
    },
    /*
    * 代码请在此处上方设计。
    * */
    {
        path: '/test',
        name: 'TestPage',
        component: TestPage,
        meta: { title: 'test', layout: "EmptyLayout" }
    },
    /*
    * 代码请在此处上方设计。
    * */

    /* 重定向到首页 */
    { path: '/', redirect: '/homePage' },

    /* 404 */
    {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: NotFound,
        meta: { title: 'NotFound', layout: 'EmptyLayout' }
    },
]

const router = createRouter({
    history: createWebHistory(),
    routes,
    scrollBehavior(to, from, savedPosition) {
        if (savedPosition) {
            return savedPosition;
        } else {
            return { top: 0 };
        }
    }
})

export default router

router.beforeEach((to, from, next) => {
    const isAuth = sessionStorage.getItem('userToken');
    const currentUser = sessionStorage.getItem('jobCode');
    const role = sessionStorage.getItem('role')
    const t = i18n.global.t // 获取翻译方法
    const titleKey = to.meta.title || 'appName'
    document.title = `${t(titleKey)} | ${t('appName')}`

    if (isAuth && to.meta.requiresAuth === false) {
        return next({ path: `/${currentUser}/dashboard` });
    }

    if (to.matched.some(record => record.meta.requiresAuth)) {
        if (!isAuth) {
            return next({
                path: '/loginAndRegister',
                query: { redirect: to.fullPath }
            });
        }
    }

    if (to.meta.validateUser) {
        const routeUser = to.params.jobCode;
        if (routeUser !== currentUser) {
            return next('/unAuthorized');
        }
    }

    if (to.meta.requiresRole) {
        if (!role) {
            return next('/loginAndRegister')
        }
        if (to.meta.requiresRole !== role) {
            return next('/unAuthorized')
        }
    }

    if (to.path === '/loginAndRegister' && isAuth) {
        return next(`/${currentUser}/dashboard`);
    }

    if (to.name === 'Verification') {
        const isAuth = sessionStorage.getItem('userToken');
        if (!isAuth) {
            return next({ path: '/loginAndRegister', query: { redirect: to.fullPath } });
        }
    }

    next();
});
